<template>
    <div>
      <el-scrollbar height="600px">
      <el-card>
        <el-row :gutter="20" class="header">
            <el-col :span="6">
              <el-input placeholder="请输入作业名称"
              style="width: 100%"
              v-model="queryInfo.name" clearable @clear="getHomeworkList"></el-input>
            </el-col>
            <el-col :span="6">
              <el-input placeholder="请输入课程名称"
              style="width: 100%"
              v-model="queryInfo.courseName" clearable @clear="getHomeworkList"></el-input>
            </el-col>
            <el-col :span="6">
              <el-input placeholder="请输入课程序号"
              style="width: 100%"
              v-model="queryInfo.courseId" clearable @clear="getHomeworkList"></el-input>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" :icon="Search" @click="getHomeworkList">搜索</el-button>
            </el-col>
          </el-row>
        <el-button type="primary" :icon="Plus" @click="dialogVisible = true">发布作业</el-button>
        <el-table :data="tableData" style="width: 100%; margin-top: 10px;">
          <el-table-column type="index" width="20" />
          <el-table-column prop="courseId" label="课程序号" width="70" />
          <el-table-column prop="courseName" label="课程名" width="80" />
          <el-table-column prop="homeworkId" width="100" v-if="false"/>
          <el-table-column prop="homeworkName" label="作业名称" width="120" />
          <el-table-column prop="startTime" label="发布日期" width="160" />
          <el-table-column prop="endTime" label="截止日期" width="160"/>
          <el-table-column prop="hupingStartTime" label="互评开始日期" width="160" />
          <el-table-column prop="hupingEndTime" label="互评截止日期" width="160"/>
          <el-table-column prop="profile" v-if="false" />
          <el-table-column label="查看">
            <template v-slot="scope">
              <el-button @click="viewDetails(scope.row)" >详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background="true"
          layout="prev, pager, next"
          :total="total"
          v-model:currentPage="queryInfo.page"
          :page-size="queryInfo.size"
          @current-change="handlePageChange"
        />
      </el-card>
      <el-dialog  v-model="dialogVisible" title="发布作业" draggable>
            <el-form :model="newHomework" label-width="140px">
                <el-form-item label="作业名称">
                <el-input v-model="newHomework.name"></el-input>
                </el-form-item>
                <el-form-item label="作业类型">
                    <el-radio-group v-model="newHomework.type">
                    <el-radio label="0">普通作业</el-radio>
                    <el-radio label="1">在线编程</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="课程序号">
                  <el-autocomplete
                    v-model="newHomework.courseId"
                    :fetch-suggestions="querySearch"
                    placeholder="请输入课程序号"
                    @select="handleSelect"
                  ></el-autocomplete>
                </el-form-item>
                <el-form-item label="作业详情">
                <el-input v-model="newHomework.profile" ></el-input>
                </el-form-item>
                <el-form-item label="互评是否匿名" v-if="newHomework.type !== '1'" disabled>
                    <el-radio-group v-model="newHomework.anonymous">
                    <el-radio label="1">匿名</el-radio>
                    <el-radio label="0">公开</el-radio>
                    </el-radio-group>
                </el-form-item>
                <div class="datetime-picker">
                  <div class="block">
                    <el-date-picker
                      v-model="newHomework.startTime"
                      type="datetime"
                      placeholder="开始时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                    />
                  </div>
                  <div class="block">
                    <el-date-picker
                      v-model="newHomework.endTime"
                      type="datetime"
                      placeholder="截止时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                    />
                  </div>
                  <div class="block" v-if="newHomework.type !== '1'" disabled>
                    <el-date-picker
                      v-model="newHomework.hupingStartTime"
                      type="datetime"
                      placeholder="互评开始时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                    />
                  </div>
                  <div class="block" v-if="newHomework.type !== '1'" disabled>
                    <el-date-picker
                      v-model="newHomework.hupingEndTime"
                      type="datetime"
                      placeholder="互评截止时间"
                      format="YYYY-MM-DD HH:mm:ss"
                      date-format="MMM DD, YYYY"
                      time-format="HH:mm"
                    />
                  </div>
              </div>
            </el-form>
            <template v-slot:footer>
                <span class="dialog-footer">
                <el-button @click="dialogVisible=false">取消</el-button>
                <el-button type="primary" @click="saveHomework">保存</el-button>
                </span>
            </template>
      </el-dialog>
    </el-scrollbar>
    </div>
  </template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, Plus } from '@element-plus/icons-vue'
import { getHomework } from '@/api/homeworks'
import { getTeacherCourse } from '@/api/getInAdd'
import { ElMessage } from 'element-plus'
import { addHomework } from '@/api/addHomeworks'

const router = useRouter()

const total = ref(0)

const currentPage = ref(1)

const queryInfo = ref({
  courseId: '',
  courseName: '',
  homeworkId: '',
  homeworkName: '',
  startTime: '',
  endTime: '',
  hupingStartTime: '',
  hupingEndTime: '',
  profile: '',
  page: currentPage,
  size: 5
})

const tableData = ref([])

const courseQuery = ref({
  courseId: '',
  homeworkName: '',
  courseName: '',
  teacherName: '',
  page: '1',
  size: 10
})

const getHomeworkList = async () => {
  const res = await getHomework(courseQuery.value)
  console.log(res)
  tableData.value = res.data.data.rows
  total.value = res.data.data.total
}

const dialogVisible = ref(false)

const newHomework = ref({
  courseId: '',
  profile: '',
  startTime: '',
  endTime: '',
  hupingStartTime: '',
  hupingEndTime: '',
  standardAnswer: '',
  type: ''
})

let courseIdAndNameMap = []

const querySearch = async (queryString, cb) => {
  if (queryString === '') {
    cb(courseIdAndNameMap)
  } else {
    const response = await getTeacherCourse()
    courseIdAndNameMap = response.data.data.map(course => ({
      value: course.course_id,
      courseName: course.name
    }))
    console.log(courseIdAndNameMap)
    cb(courseIdAndNameMap)
  }
}

const form = (inputDateString) => {
  const inputDate = new Date(inputDateString)
  const year = inputDate.getFullYear()
  const month = (inputDate.getMonth() + 1).toString().padStart(2, '0') // 月份是从0开始的，所以要加1
  const day = inputDate.getDate().toString().padStart(2, '0')
  const hours = inputDate.getHours().toString().padStart(2, '0')
  const minutes = inputDate.getMinutes().toString().padStart(2, '0')
  const seconds = inputDate.getSeconds().toString().padStart(2, '0')
  const formattedDateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  return formattedDateString
}

const saveHomework = async () => {
  if (!newHomework.value.name || !newHomework.value.courseId) {
    ElMessage.error('作业名称和课程序号不能为空')
    return
  }
  newHomework.value.startTime = form(newHomework.value.startTime)
  newHomework.value.endTime = form(newHomework.value.startTime)
  newHomework.value.hupingStartTime = form(newHomework.value.startTime)
  newHomework.value.hupingEndTime = form(newHomework.value.startTime)
  const res = await addHomework(newHomework.value)
  console.log(res)
  tableData.value.push({ ...newHomework })
  if (res.data.code === 0) {
    ElMessage.success('创建成功！')
  } else {
    ElMessage.error('作业创建失败！')
  }
  newHomework.value.name = ''
  newHomework.value.courseId = ''
  newHomework.value.courseName = ''
  newHomework.value.profile = ''
  dialogVisible.value = false
}

const viewDetails = (row) => {
  console.log('查看详情', row)
  if (row.type === '1') {
    router.push({ name: 'HomeworkDetailCodingTeacher', params: { homeworkId: row.homeworkId } })
  } else {
    router.push({ name: 'HomeworkDetail', params: { homeworkId: row.homeworkId } })
  }
}

const handlePageChange = () => {
  getHomeworkList()
}

onMounted(getHomeworkList)
</script>

<style>
.header{
  padding-bottom: 16px;
}
.datetime-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
  justify-content: space-around;
  align-items: stretch;
}
.datetime-picker .block {
  padding: 10px 0;
  text-align: center;
}
</style>
